﻿function registerSelectAppointmentPlan(form) {
    let amis = amisRequire('amis/embed');
    let amisLib = amisRequire('amis');
    let React = amisRequire('react');

    function getCurrentPlan(data, currentPlanId) {
        if (data.rows) {
            for (const row of data.rows) {
                for (const plan of row) {
                    if (plan.id === currentPlanId) {
                        return plan;
                    }
                }
            }
        }
    }

    function SelectAppointmentPlan(props) {
        const { examOid, deviceOid, selectedDate, initPlan, selectedPlan, loadCount, url } = props.data;
        // initPlan 主页面加载时获取
        // selectedPlan 来自表单数据域，第一次打开弹窗时与initPlan相同
        // loadCount  初始为零，表格每渲染一次，loadCount+1，也就是打开一次弹窗
        // deviceOid  外部选中的设备oid
        // selectedDate  外部选中的日期
        // selectedPlan 在外部表单储存选中的计划oid

        const createVue = React.useCallback((dom) => {
            return new Vue({
                el: dom.current,
                data: function () {
                    return {
                        columns: [],
                        rows: [],
                        currentPlan: '',
                        selectedOid: initPlan,  // 当前选中
                        url: url,// 最初为initPlan，后被更改
                        examOid: examOid,
                        diviceOids: deviceOid,
                        selectedDate: selectedDate,
                        selectedPlan: null,
                        loading: false
                    }
                },
                methods: {
                    // 单元格点击
                    cellClicked(cell) {
                        if (!this.loading) {
                            let that = this;
                            let id = cell.id;
                            if (id) { // 单元格有排班
                                if (that.selectedPlan && that.selectedPlan.currentCount > 0) {
                                    that.selectedPlan.currentCount--;
                                }
                                that.selectedPlan = cell;
                                that.selectedPlan.currentCount++;

                                if (that.selectedOid != id){  // 选中更改
                                    that.selectedOid = id;
                                    that.selectedDate = selectedDate;
                                }
                                else { // 取消选中
                                    that.selectedOid = '';
                                    that.selectedPlan.currentCount--;
                                    that.selectedPlan = null;
                                    that.selectedDate = parseInt(Date.now() / 1000);
                                }
                                that.saveChange(cell);
                            }
                        }
                    },
                    // 将更改保存到dialog数据域
                    saveChange(cell) {
                        var that = this;
                        form.doAction({
                            actionType: "setValue",
                            componentId: "appointment-plan-dialog",
                            args: {
                                value: {
                                    planResult: that.selectedOid
                                }
                            }
                        })
                    },
                    //(弃用) 保存操作更改，更新数据模型
                    saveChange1(cell) {
                        let that = this;
                        this.loading = true;
                        $.get(that.url + `api/exam-detail/save-appointment?examOid=` + examOid + "&planOid=" + that.selectedOid)
                            .then((res) => {
                                if (res.status == 0) {
                                    // 更新amis 
                                    form.doAction({
                                        actionType: "setValue",
                                        componentId: "u:47613009fb7c",
                                        args: {
                                            value: {
                                                appointmentNumber: res.data.appointmentNumber,
                                                appointmentPlan: that.selectedOid,
                                                appointmentName: res.data.appointmentName,
                                                appointmentDate: that.selectedDate
                                            }
                                        }
                                    });
                                   
                                    this.loading = false;
                                }
                            });
                    },
                    // 单元格样式
                    cellClassName(cell) {
                        let that = this;
                        // 根据vue内部selectedOid ，确定被选中、未被选中、未排班等单元格样式
                        if (cell.id) {
                            if (cell.id != that.selectedOid) {
                                return "plan"
                            }
                            else {
                                return "plan selected"
                            }
                        } else {
                            return "plan";
                        }
                    },
                    colculateRow(row) {
                        return [...row.slice(1)];
                    },
                    refresh(data) {
                        let that = this;
                        that.columns = data.columns;
                        that.rows = data.rows;
                        that.currentPlan = data.currentPlan;
                        that.deviceOids = data.deviceOids;
                        that.selectedDate = data.selectedDate;
                        that.selectedPlan = getCurrentPlan(data, initPlan);
                    }
                }
            });
        }, []); // 这样只会编译一次，相当于将方法缓存起来

        let dom = React.useRef(null);// 等于是创建对react组件绑定dom的引用

        let [initialized, setInitialized] = React.useState(false); // 声明状态，和状态的设置器
        let [data, setData] = React.useState(null); // 后面参数为默认值
        let [myVue, setMyVue] = React.useState(null);// 后面参数为默认值

        let str = `
            <table v-if="rows.length>0">
                <thead>
                    <tr>
                        <th>时段</th>
                        <th v-for="(item,index) in columns" :key="item.oid">{{item.deviceName}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,index) in rows" :key="index">
                        <td class="time-interval-text" :key="item[0].timeIntervalOid">
                            <b>{{item[0].interalName}}</b>
                        </td>
                        <td v-for="(cell,cellIndex) in colculateRow(item)" :class='cellClassName(cell)' :key="cellIndex" @click="cellClicked(cell)">
                            <div v-if="cell.id" class="plan-progress">
                                <div class="plan-progress-value" :style="'width:'+(cell.currentCount/cell.maxCount*100)+'%'"></div>
                                <div class="plan-progress-text">{{cell.currentCount}}/{{cell.maxCount}}</div>
                            </div>
                            <div v-else class="noplan">无</div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div v-if="rows.length===0" class="no-data pt-2">暂无预约时段</div>
        `;

        // 副作用，当组件内初加载时，从上到下，每一个副作用都会执行
        // 第二个参数，为一个数组，空数组，啥都不监控，也就相当于啥都不会改变，不改变就只会在第一次加载组件时执行一次。

        React.useEffect(() => {
            if (data) {
                myVue?.refresh(data);// 不为空则执行刷新
            }
        }, [data]); // data变量改变，则触发次副作用执行。

        React.useEffect(function () {
            $.get(url + `api/exam-detail/get-appointment-data?examOid=` + examOid + `&deviceOids=` + deviceOid + `&selectedDate=` + selectedDate)
                .then(function (res) {
                    dom.current.innerHTML = str;
                    if (!initialized) {
                        setMyVue(createVue(dom));
                        setInitialized(true);
                    }
                    res.data.deviceOids = deviceOid;
                    res.data.selectedDate = selectedDate;
                    setData(res.data);
                });
        }, [examOid, deviceOid, selectedDate, initPlan, url]);  // 监听参数变化  变化了就重新请求渲染

        return React.createElement('div', {
            ref: dom,
            className: 'appointment-plan-container'
        });
    }

    amisLib.Renderer({
        test: /(^|\/)SelectAppointmentPlan/
    })(SelectAppointmentPlan);
}

